package com.boat.starter.web.excepton;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.boat.framework.base.api.Response;
import com.boat.framework.base.exception.CommonErrorCode;
import com.boat.framework.common.monitor.event.PageNoFinded;
import com.boat.framework.common.monitor.logs.EventLog;

import lombok.extern.slf4j.Slf4j;

/**
 * 404处理器
 * 
 * 当url错误时，不会经过spring拦截器，会直接触发此异常处理器
 * 
 * 使用方法。因starter加载顺序限制，此拦截器需要在业务包使用@Bean手动引用
 * 
 * @author 周江
 *
 */
@Slf4j
@Controller
public class PageNoFindExceptonHandler extends AbstractErrorController {
	public PageNoFindExceptonHandler(ErrorAttributes errorAttributes) {
		super(errorAttributes);
	}

	@RequestMapping(value = "/error", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Response<Object> handleError(HttpServletRequest request) {
		Map<String, Object> errorAttributes = super.getErrorAttributes(request, ErrorAttributeOptions.defaults());
		String uri = errorAttributes.get("path").toString();
		log.warn("404请求，请求地址不正确：{}", uri);
		
		//记录监控日志
		EventLog.log(new PageNoFinded(uri));
		
		return Response.failed(CommonErrorCode.PAGE_NO_FIND.getCode(),
				CommonErrorCode.PAGE_NO_FIND.getMessage(new String[] { uri }));
	}

}
